package com.meisupic.copyright.service.impl;

import com.meisupic.copyright.domain.bo.SysUser;
import com.meisupic.copyright.domain.po.MemberCategoryPo;
import com.meisupic.copyright.domain.po.VipMemberPo;
import com.meisupic.copyright.domain.po.VipOrder;
import com.meisupic.copyright.domain.vo.MemberCategoryMapVo;
import com.meisupic.copyright.domain.vo.MemberCategoryVo;
import com.meisupic.copyright.domain.vo.VipMemberVo;
import com.meisupic.copyright.domain.vo.VipOrderVo;
import com.meisupic.copyright.exception.BizException;
import com.meisupic.copyright.repo.MemberCategoryRepo;
import com.meisupic.copyright.repo.VipMemberRepo;
import com.meisupic.copyright.service.IAccountService;
import com.meisupic.copyright.service.VipMemberService;
import com.meisupic.copyright.util.BeanMapper;
import com.meisupic.copyright.util.DateUtil;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VipMemberServiceImpl implements VipMemberService {

  @Autowired
  private VipMemberRepo vipMemberRepo;

  @Autowired
  private MemberCategoryRepo memberCategoryRepo;

  @Autowired
  private IAccountService accountService;


  @Override
  public MemberCategoryMapVo getMemberCategoryMap() {
    List<MemberCategoryPo> memberCategoryPoList = memberCategoryRepo.findAll();
    MemberCategoryMapVo memberCategoryMapVo = new MemberCategoryMapVo();
    List<MemberCategoryVo> memberCategoryVoList = BeanMapper
        .mapList(memberCategoryPoList, MemberCategoryVo.class);
    memberCategoryVoList.forEach(
        memberCategoryVo -> memberCategoryMapVo.put(memberCategoryVo.getId(), memberCategoryVo));
    return memberCategoryMapVo;
  }

  /**
   * 完成会员购买的功能
   */
  @Override
  public void completeOrder(Long userId, String orderNo, String memberCategoryId) {
    MemberCategoryPo memberCategory = memberCategoryRepo.findOne(Long.valueOf(memberCategoryId));
    Date invalidDate = DateUtil.getOffsiteDate(new Date(), Calendar.YEAR, 1);
    VipMemberPo vipMemberPo = new VipMemberPo();
    vipMemberPo.setLeftAmount(memberCategory.getServiceTotal());
    vipMemberPo.setTotal(memberCategory.getServiceTotal());
    vipMemberPo.setMemberCategoryId(memberCategory.getId());
    vipMemberPo.setMemberCategoryName(memberCategory.getCategoryName());
    vipMemberPo.setOrderNo(orderNo);
    vipMemberPo.setUserId(userId);
    vipMemberPo.setExpiryDate(invalidDate);
    vipMemberPo.setCreateDate(new Date());
    vipMemberRepo.save(vipMemberPo);
  }

  @Override
  public List<VipMemberVo> getVipMember(Long userId) {
    List<VipMemberPo> vipMemberPos = vipMemberRepo.findByUserId(userId);
    return BeanMapper.mapList(vipMemberPos, VipMemberVo.class);
  }

  /**
   * 判断是否是Vip
   */
  @Override
  public boolean isVip(Long userId) {
    if (userId == null) {
      return false;
    }
    List<VipMemberPo> vipMemberPos = vipMemberRepo
        .findVipMemberPosByExpiryDateAfterAndUserId(new Date(), userId);

    return CollectionUtils.isNotEmpty(vipMemberPos);
  }

  /**
   * 判断vip服务是否可用
   *
   * @param userId 用户id
   * @param requireNum 需要的数量
   */
  @Override
  public boolean vipServiceIsAvailable(Long userId, Integer requireNum) {
    List<VipMemberPo> vipMemberPos = vipMemberRepo
        .findVipMemberPosByExpiryDateAfterAndUserId(new Date(), userId);
    if (vipMemberPos.stream().anyMatch(vipMemberPo -> vipMemberPo.getTotal() == -1)) {
      return true;
    }
    int aveilableNum = 0;

    for (VipMemberPo vipMemberPo : vipMemberPos) {

      if (vipMemberPo.getTotal() == -1) {
        continue;
      }
      aveilableNum += vipMemberPo.getLeftAmount();

    }

    return aveilableNum >= requireNum;
  }

  @Override
  public void reduceCount(Long userId, Integer num) {
    List<VipMemberPo> vipMemberPos = vipMemberRepo
        .findVipMemberPosByExpiryDateAfterAndUserId(new Date(), userId);
    if (vipMemberPos.stream().anyMatch(vipMemberPo -> vipMemberPo.getTotal() == -1)) {
      return;
    }
    if (CollectionUtils.isNotEmpty(vipMemberPos)) {
      vipMemberPos.sort(Comparator.comparing(VipMemberPo::getExpiryDate));
      Integer reduceNum = num;
      for (VipMemberPo vipMemberPo : vipMemberPos) {
        if (vipMemberPo.getLeftAmount() == 0) {
          continue;
        }
        if (vipMemberPo.getLeftAmount() < reduceNum) {
          reduceNum = num - vipMemberPo.getLeftAmount();
          vipMemberPo.setLeftAmount(0);
          vipMemberRepo.save(vipMemberPo);
        } else {
          vipMemberPo.setLeftAmount(vipMemberPo.getLeftAmount() - reduceNum);
          vipMemberRepo.save(vipMemberPo);
          break;
        }
      }
    }

  }

  @Override
  public VipOrderVo createOrder(Long memberCategoryId, SysUser user) {
    MemberCategoryPo memberCategoryPo = memberCategoryRepo.findOne(memberCategoryId);

    if (memberCategoryPo == null) {
      throw new BizException("无对应的vip类型");
    }
    VipOrder vipOrder = new VipOrder();
    vipOrder.setUserId(user.getId());
    vipOrder.setPayStatus(false);
    vipOrder.setUserName(user.getUsername());
    vipOrder.setMemberCategoryId(memberCategoryId);
    vipOrder.setOrderPrice(memberCategoryPo.getDiscountPrice());
    accountService.addVipOrder(vipOrder);

    VipOrderVo vipOrderVo = BeanMapper.map(vipOrder, VipOrderVo.class);
    vipOrderVo.setMemberCategoryName(memberCategoryPo.getCategoryName());
    vipOrderVo.setServiceTotal(memberCategoryPo.getServiceTotal().toString());
    return vipOrderVo;
  }


}
